import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:extended_image/extended_image.dart';
import 'dart:io';
import 'package:openim/routes/app_pages.dart';
import 'package:openim_common/openim_common.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';
import 'package:latlong2/latlong.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:video_player/video_player.dart';
import '../location_picker/location_picker_view.dart';
import '../../models/circle_models.dart';
import 'notification_logic.dart';

class NotificationPage extends StatelessWidget {
  final logic = Get.find<NotificationLogic>();

  NotificationPage({super.key});

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        backgroundColor: Styles.c_F8F9FA,
        appBar: AppBar(
          backgroundColor: Styles.c_FFFFFF,
          elevation: 0,
          title: Row(
            children: [
              SizedBox(width: 16.w),
              Expanded(
                child: Container(
                  height: 36.h,
                  decoration: BoxDecoration(
                    color: Styles.c_F8F9FA,
                    borderRadius: BorderRadius.circular(18.r),
                  ),
                  child: TextField(
                    textAlign: TextAlign.center,
                    readOnly: true,
                    decoration: InputDecoration(
                      hintText: '搜索帖子',
                      hintStyle: TextStyle(
                        color: Styles.c_8E9AB0,
                        fontSize: 14.sp,
                      ),
                      prefixIcon: Icon(
                        Icons.search,
                        color: Styles.c_8E9AB0,
                        size: 20.w,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 8.h,
                      ),
                    ),
                    onTap: () {
                      final circleId = logic
                          .getCircleByType(logic.currentCircleType.value)
                          ?.id
                          .toString();
                      Get.toNamed(
                        AppRoutes.postSearch,
                        arguments: {'circleId': circleId},
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
          centerTitle: false,
          actions: [
              // 通知图标按钮
            Obx(() => Stack(
              children: [
                IconButton(
                  icon: Icon(Icons.notifications, color: Styles.c_0C1C33),
                  onPressed: () {
                    _showNotificationPanel(context);
                  },
                ),
                if (logic.unreadNotificationCount.value > 0)
                  Positioned(
                    right: 8,
                    top: 8,
                    child: Container(
                      padding: EdgeInsets.all(2.w),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      constraints: BoxConstraints(
                        minWidth: 16.w,
                        minHeight: 16.h,
                      ),
                      child: Text(
                        '${logic.unreadNotificationCount.value}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 10.sp,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
              ],
            )),
            IconButton(
              icon: Icon(Icons.add, color: Styles.c_0C1C33),
              onPressed: () {
                _showPublishDialog(Get.context!);
              },
            ),
            // IconButton(
            //   icon: Icon(Icons.local_offer, color: Styles.c_0C1C33),
            //   onPressed: () {
            //     _showTagManagementDialog(context);
            //   },
            // ),
          ],
          bottom: TabBar(
            labelColor: Styles.c_0C1C33,
            unselectedLabelColor: Styles.c_8E9AB0,
            indicatorColor: Styles.c_0C1C33,
            tabs: const [
              Tab(text: '城市圈'),
              Tab(text: '国家圈'),
              Tab(text: '全球圈'),
            ],
            onTap: (index) {
              logic.switchCircleType(CircleType.values[index]);
            },
          ),
        ),
        body: Column(
          children: [
            // 标签筛选栏
            Container(
              height: 50.h,
              color: Styles.c_FFFFFF,
              child: Obx(() {
                // 获取当前选中的标签ID，这样Obx可以正确追踪变化
                final currentSelectedTagId = logic.selectedTagId.value;
                
                return ListView.builder(
                  scrollDirection: Axis.horizontal,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  itemCount: logic.availableTags.length + 1,
                  itemBuilder: (context, index) {
                    if (index == 0) {
                      return _buildTagChip(
                        '全部',
                        currentSelectedTagId.isEmpty,
                        () => logic.selectTag(''),
                      );
                    }
                    final tag = logic.availableTags[index - 1];
                    return _buildTagChip(
                      tag.name,
                      currentSelectedTagId == tag.id,
                      () => logic.selectTag(tag.id),
                      color: tag.color,
                    );
                  },
                );
              }),
            ),
            // 分隔线
            Container(
              height: 1.h,
              color: Styles.c_F8F9FA,
            ),
            // 帖子列表
            Expanded(
              child: TabBarView(
                children: [
                  _buildPostList(context, CircleType.city),
                  _buildPostList(context, CircleType.country),
                  _buildPostList(context, CircleType.global),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTagChip(String label, bool isSelected, VoidCallback onTap, {String? color}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.only(right: 8.w, top: 8.h, bottom: 8.h),
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
        decoration: BoxDecoration(
          color: isSelected ? Styles.c_0C1C33 : Styles.c_F8F9FA,
          borderRadius: BorderRadius.circular(16.r),
          border: color != null
              ? Border.all(color: Color(int.parse('0xFF${color.substring(1)}')))
              : null,
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Styles.c_FFFFFF : Styles.c_0C1C33,
            fontSize: 12.sp,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }


  Widget _buildPostList(BuildContext context, CircleType circleType) {
  return RefreshIndicator(
    onRefresh: () => logic.refreshPosts(circleType),
    child: Obx(() {
      final posts = logic.getPostsByType(circleType);
      if (posts.isEmpty) {
        // 空状态时也需要可滚动的Widget来支持下拉刷新
        final isSearching = logic.searchKeyword.value.trim().isNotEmpty;
        final kw = logic.searchKeyword.value.trim();
        final hasTag = logic.selectedTagId.value.isNotEmpty;

        return SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Container(
            height: MediaQuery.of(context).size.height * 0.6,
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    isSearching ? Icons.search_off : Icons.post_add,
                    size: 64.w,
                    color: Styles.c_8E9AB0,
                  ),
                  16.verticalSpace,
                  Text(
                    isSearching
                        ? '没有找到与“$kw”相关的帖子'
                        : '暂无${circleType.displayName}帖子',
                    style: TextStyle(
                      color: Styles.c_8E9AB0,
                      fontSize: 16.sp,
                    ),
                  ),
                  8.verticalSpace,
                  Text(
                    isSearching
                        ? (hasTag ? '当前启用了标签筛选，可能影响结果' : '试试更换关键词或清除搜索')
                        : '下拉刷新获取最新内容',
                    style: TextStyle(
                      color: Styles.c_8E9AB0,
                      fontSize: 12.sp,
                    ),
                  ),
                  16.verticalSpace,
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      if (isSearching)
                        Padding(
                          padding: EdgeInsets.only(right: 8.w),
                          child: OutlinedButton.icon(
                            onPressed: () => logic.searchPosts(''),
                            icon: Icon(Icons.clear),
                            label: Text('清除搜索'),
                          ),
                        ),
                      if (hasTag)
                        Padding(
                          padding: EdgeInsets.only(right: 8.w),
                          child: OutlinedButton.icon(
                            onPressed: () => logic.selectTag(''),
                            icon: Icon(Icons.label_off_outlined),
                            label: Text('清除标签'),
                          ),
                        ),
                      ElevatedButton.icon(
                        onPressed: () => _showPublishDialog(Get.context!),
                        icon: Icon(Icons.edit_outlined),
                        label: Text(isSearching ? '去发布相关内容' : '发布第一条帖子'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      }

      return ListView.builder(
        physics: AlwaysScrollableScrollPhysics(), // 确保可以下拉刷新
        padding: EdgeInsets.symmetric(vertical: 8.h),
        itemCount: posts.length,
        itemBuilder: (context, index) {
          return _buildPostItem(posts[index]);
        },
      );
    }),
  );
}

  Widget _buildPostItem(CirclePost post) {
    return Container(
      margin: EdgeInsets.only(bottom: 8.h),
      padding: EdgeInsets.all(16.w),
      color: Styles.c_FFFFFF,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息行
          Row(
            children: [
              AvatarView(
                url: post.userAvatar,
                text: logic.getPostDisplayName(post),
                width: 40.w,
                height: 40.h,
              ),
              12.horizontalSpace,
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    logic.getPostDisplayName(post).toText..style = Styles.ts_0C1C33_17sp_medium,
                    4.verticalSpace,
                    post.timeAgo.toText..style = Styles.ts_8E9AB0_12sp,
                  ],
                ),
              ),
              // 只有当前用户的帖子才显示菜单按钮
              if (logic.isCurrentUserPost(post.userId))
                PopupMenuButton(
                  icon: Icon(Icons.more_horiz, color: Styles.c_8E9AB0),
                  itemBuilder: (context) {
                    return [
                      PopupMenuItem(
                        value: 'edit',
                        child: Row(
                          children: [
                            Icon(Icons.edit, size: 16.w, color: Styles.c_0C1C33),
                            8.horizontalSpace,
                            Text('编辑'),
                          ],
                        ),
                      ),
                      PopupMenuItem(
                        value: 'delete',
                        child: Row(
                          children: [
                            Icon(Icons.delete, size: 16.w, color: Colors.red),
                            8.horizontalSpace,
                            Text('删除', style: TextStyle(color: Colors.red)),
                          ],
                        ),
                      ),
                    ];
                  },
                  onSelected: (value) {
                    switch (value) {
                      case 'edit':
                        _showEditPostDialog(post);
                        break;
                      case 'delete':
                        _showDeleteConfirmDialog(post);
                        break;
                    }
                  },
                ),
            ],
          ),
          16.verticalSpace,
          // 标签显示
          if (post.tags.isNotEmpty)
            Wrap(
              spacing: 8.w,
              runSpacing: 4.h,
              children: post.tags.map((tag) => Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                decoration: BoxDecoration(
                  color: tag.color != null
                      ? Color(int.parse('0xFF${tag.color!.substring(1)}')).withOpacity(0.1)
                      : Styles.c_F8F9FA,
                  borderRadius: BorderRadius.circular(12.r),
                  border: tag.color != null
                      ? Border.all(
                          color: Color(int.parse('0xFF${tag.color!.substring(1)}')),
                          width: 0.5,
                        )
                      : null,
                ),
                child: Text(
                  tag.name,
                  style: TextStyle(
                    color: tag.color != null
                        ? Color(int.parse('0xFF${tag.color!.substring(1)}'))
                        : Styles.c_0C1C33,
                    fontSize: 10.sp,
                  ),
                ),
              )).toList(),
            ),
          if (post.tags.isNotEmpty) 12.verticalSpace,
          // 内容文本
          if (post.content.isNotEmpty)
            Padding(
              padding: EdgeInsets.only(bottom: 12.h),
              child: post.content.toText..style = Styles.ts_0C1C33_14sp,
            ),
             // 新增：位置展示
          if ((post.locationAddress ?? '').isNotEmpty)
          Padding(
            padding: EdgeInsets.only(bottom: 12.h),
            child: Row(
              children: [
                Icon(Icons.place, size: 16.w, color: Styles.c_8E9AB0),
                6.horizontalSpace,
                Expanded(
                  child: Text(
                    post.locationAddress!,
                    style: Styles.ts_8E9AB0_12sp,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
          
          // 图片网格
          if (post.images.isNotEmpty)
            _buildImageGrid(post.images),
           // 新增：视频展示（仅第一条）
          if (post.videos.isNotEmpty) ...[
            12.verticalSpace,
            _InlineVideoPlayer(url: post.videos.first),
          ],
          16.verticalSpace,
          // 操作按钮行
          Row(
            children: [
              _buildActionButton(
                post.isLiked ? Icons.favorite : Icons.favorite_border,
                post.likeCount.toString(),
                post.isLiked,
                () => logic.toggleLike(post.id),
              ),
              24.horizontalSpace,
              _buildActionButton(
                Icons.share_outlined,
                post.shareCount.toString(),
                false,
                () => logic.sharePost(post.id),
              ),
              Spacer(),
              IconButton(
                icon: Icon(
                  post.isBookmarked ? Icons.bookmark : Icons.bookmark_border,
                  color: post.isBookmarked ? Styles.c_FFB300 : Styles.c_8E9AB0,
                ),
                onPressed: () => logic.toggleBookmark(post.id),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildActionButton(
    IconData icon,
    String count,
    bool isActive,
    VoidCallback onTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Icon(
            icon,
            size: 20.w,
            color: isActive ? Colors.red : Styles.c_8E9AB0,
          ),
          4.horizontalSpace,
          Text(
            count,
            style: TextStyle(
              color: isActive ? Colors.red : Styles.c_8E9AB0,
              fontSize: 12.sp,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageGrid(List<String> images) {
    if (images.isEmpty) return const SizedBox.shrink();
    
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: images.length == 1 ? 1 : (images.length == 2 ? 2 : 3),
        crossAxisSpacing: 4.w,
        mainAxisSpacing: 4.h,
        childAspectRatio: 1,
      ),
      itemCount: images.length > 9 ? 9 : images.length,
      itemBuilder: (context, index) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(8.r),
          child: Stack(
            fit: StackFit.expand,
            children: [
              Image.network(
                images[index],
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Styles.c_F0F2F6,
                    child: Icon(
                      Icons.image_not_supported,
                      color: Styles.c_8E9AB0,
                    ),
                  );
                },
              ),
              if (index == 8 && images.length > 9)
                Container(
                  color: Colors.black54,
                  child: Center(
                    child: Text(
                      '+${images.length - 9}',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }

  void _showPublishDialog(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _PublishPostDialog(),
    );
  }

  void _showCommentDialog(CirclePost post) {
    // 显示评论对话框
    showModalBottomSheet(
      context: Get.context!,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        height: Get.height * 0.7,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(16.w),
              child: Text(
                '评论 (${post.commentCount})',
                style: Styles.ts_0C1C33_17sp_medium,
              ),
            ),
            Expanded(
              child: Center(
                child: Text(
                  '评论功能开发中...',
                  style: Styles.ts_8E9AB0_14sp,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

    // 显示通知面板
  void _showNotificationPanel(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _NotificationPanel(),
    );
  }

   // 显示编辑帖子对话框
  void _showEditPostDialog(CirclePost post) {
    showModalBottomSheet(
      context: Get.context!,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _EditPostDialog(post: post),
    );
  }

  // 显示删除确认对话框
  void _showDeleteConfirmDialog(CirclePost post) {
    Get.dialog(
      AlertDialog(
        title: Text('确认删除'),
        content: Text('确定要删除这条帖子吗？删除后无法恢复。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Get.back();
              await logic.deletePost(post.id);
            },
            child: Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}

// 发布帖子对话框
class _PublishPostDialog extends StatefulWidget {
  @override
  _PublishPostDialogState createState() => _PublishPostDialogState();
}

class _PublishPostDialogState extends State<_PublishPostDialog> {
  final TextEditingController _contentController = TextEditingController();
  final logic = Get.find<NotificationLogic>();
  CircleType selectedCircleType = CircleType.global;
  List<PostTag> selectedTags = [];
  @override
  void initState() {
    super.initState();
    // 设置默认圈子类型为当前圈子类型
    selectedCircleType = logic.currentCircleType.value;
    
    // 设置默认标签为当前圈子类型的第一个标签
    final availableTags = logic.getTagsByType(selectedCircleType);
    if (availableTags.isNotEmpty) {
      selectedTags = [availableTags.first];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: Get.height * 1, // 从0.8增加到0.9，提供更多垂直空间
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                TextButton(
                  onPressed: () => Get.back(),
                  child: Text('取消', style: Styles.ts_8E9AB0_14sp),
                ),
                Spacer(),
                Text('发布帖子', style: Styles.ts_0C1C33_17sp_medium),
                Spacer(),
                TextButton(
                  onPressed: _publishPost,
                  child: Text('发布', style: Styles.ts_0C1C33_14sp_medium),
                ),
              ],
            ),
          ),
          Divider(height: 1.h),
          // 圈子类型选择
          Container(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('选择圈子类型', style: Styles.ts_0C1C33_14sp_medium),
                12.verticalSpace,
                Row(
                  children: CircleType.values.map((type) => 
                    GestureDetector(
                      onTap: () => setState(() => selectedCircleType = type),
                      child: Container(
                        margin: EdgeInsets.only(right: 12.w),
                        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                        decoration: BoxDecoration(
                          color: selectedCircleType == type ? Styles.c_0C1C33 : Styles.c_F8F9FA,
                          borderRadius: BorderRadius.circular(20.r),
                        ),
                        child: Text(
                          type.displayName,
                          style: TextStyle(
                            color: selectedCircleType == type ? Colors.white : Styles.c_0C1C33,
                            fontSize: 14.sp,
                          ),
                        ),
                      ),
                    ),
                  ).toList(),
                ),
              ],
            ),
          ),
          // 标签选择
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text('选择标签', style: Styles.ts_0C1C33_14sp_medium),
                    Spacer(),
                    // TextButton(
                    //   onPressed: _showAddTagDialog,
                    //   child: Text('+ 添加标签', style: Styles.ts_0C1C33_12sp),
                    // ),
                  ],
                ),
                8.verticalSpace,
                Obx(() => Wrap(
                  spacing: 8.w,
                  runSpacing: 8.h,
                  children: logic.getTagsByType(selectedCircleType).map((tag) => 
                    GestureDetector(
                      onTap: () => _toggleTag(tag),
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                        decoration: BoxDecoration(
                          color: selectedTags.contains(tag) ? Styles.c_0C1C33 : Styles.c_F8F9FA,
                          borderRadius: BorderRadius.circular(16.r),
                          border: tag.color != null
                              ? Border.all(
                                  color: Color(int.parse('0xFF${tag.color!.substring(1)}')),
                                )
                              : null,
                        ),
                        child: Text(
                          tag.name,
                          style: TextStyle(
                            color: selectedTags.contains(tag) ? Colors.white : Styles.c_0C1C33,
                            fontSize: 12.sp,
                          ),
                        ),
                      ),
                    ),
                  ).toList(),
                )),
              ],
            ),
          ),
          16.verticalSpace,
          // 内容输入
          Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Column(
                children: [
                  // 文本输入框 - 移到图片预览上方
                  Expanded(
                    child: TextField(
                      controller: _contentController,
                      maxLines: null,
                      expands: true,
                      textAlignVertical: TextAlignVertical.top,
                      decoration: InputDecoration(
                        hintText: '分享你的想法...',
                        hintStyle: Styles.ts_8E9AB0_14sp,
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  // 已选择的媒体预览区域 - 移到文本输入框下方
                  Obx(() {
                    bool hasImages = logic.selectedImageFiles.isNotEmpty;
                    bool hasVideo = logic.selectedVideoFile.value != null;
                    
                    if (!hasImages && !hasVideo) {
                      return const SizedBox.shrink();
                    }
                    
                    return Container(
                      alignment: Alignment.centerLeft,
                      margin: EdgeInsets.only(top: 16.h),
                      child: Column(
                        children: [
                          // 视频预览（如果有）
                          if (hasVideo) _buildVideoPreview(),
                          // 图片预览（如果有）
                          if (hasImages) _buildSelectedImagesGrid(),
                        ],
                      ),
                    );
                  }),
                ],
              ),
            ),
          ),
          // 位置显示区域
          Obx(() {
            if (logic.selectedLocationAddress.value.isEmpty) {
              return const SizedBox.shrink();
            }
            
            return Container(
              margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                color: Styles.c_F8F9FA,
                borderRadius: BorderRadius.circular(8.r),
                border: Border.all(color: Styles.c_E8EAEF),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.location_on,
                    color: Styles.c_1B72EC,
                    size: 16.w,
                  ),
                  8.horizontalSpace,
                  Expanded(
                    child: Text(
                      logic.selectedLocationAddress.value,
                      style: Styles.ts_0C1C33_14sp,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  8.horizontalSpace,
                  GestureDetector(
                    onTap: () {
                      // 清除位置
                      logic.selectedLocation.value = null;
                      logic.selectedLocationAddress.value = '';
                    },
                    child: Icon(
                      Icons.close,
                      color: Styles.c_8E9AB0,
                      size: 16.w,
                    ),
                  ),
                ],
              ),
            );
          }),
          // 底部工具栏
          Container(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                IconButton(
                  onPressed: () {
                    // 选择图片
                    _selectImages();
                  },
                  icon: Icon(Icons.image, color: Styles.c_8E9AB0),
                ),
                IconButton(
                  onPressed: () {
                    // 选择视频
                    _selectVideo();
                  },
                  icon: Icon(Icons.videocam, color: Styles.c_8E9AB0),
                ),
                IconButton(
                  onPressed: () {
                    // 添加位置
                    _selectLocation();
                  },
                  icon: Icon(Icons.location_on, color: Styles.c_8E9AB0),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _toggleTag(PostTag tag) {
    setState(() {
      if (selectedTags.contains(tag)) {
        selectedTags.remove(tag);
      } else {
        // 确保不会添加重复标签
        if (!selectedTags.any((existingTag) => existingTag.id == tag.id)) {
          selectedTags.add(tag);
        }
      }
    });
  }

  Future<void> _publishPost() async {
    if (_contentController.text.trim().isEmpty) {
      Get.snackbar('提示', '请输入帖子内容');
      return;
    }

    // 显示发布进度对话框
    Get.dialog(
      const Center(
        child: CircularProgressIndicator(),
      ),
      barrierDismissible: false,
    );

    try {
      // 先上传图片
      List<String> uploadedImageUrls = [];
      if (logic.selectedImageFiles.isNotEmpty) {
        for (var imageFile in logic.selectedImageFiles) {
          try {
            // 使用OpenIM SDK的上传方法，与聊天保持一致
            final compressedFile = await IMUtils.compressImageAndGetFile(File(imageFile.path));
            if (compressedFile != null) {
              String putID = const Uuid().v4();
              final result = await OpenIM.iMManager.uploadFile(
                id: putID,
                filePath: compressedFile.path,
                fileName: compressedFile.path.split('/').last,
              );
              
              if (result != null && result.isNotEmpty) {
                // 解析返回的JSON获取URL
                final resultData = jsonDecode(result);
                final url = resultData['url'];
                if (url != null && url.isNotEmpty) {
                  uploadedImageUrls.add(url);
                  debugPrint('图片上传成功: $url');
                }
              }
            }
          } catch (e) {
            debugPrint('图片上传失败: $e');
            // 继续上传其他图片
          }
        }
      }

      // 上传视频
      String? uploadedVideoUrl;
      if (logic.selectedVideoFile.value != null) {
        try {
          // 使用OpenIM SDK的上传方法，与聊天保持一致
          String putID = const Uuid().v4();
          final result = await OpenIM.iMManager.uploadFile(
            id: putID,
            filePath: logic.selectedVideoFile.value!.path,
            fileName: logic.selectedVideoFile.value!.path.split('/').last,
          );
          
          if (result != null && result.isNotEmpty) {
            // 解析返回的JSON获取URL
            final resultData = jsonDecode(result);
            final url = resultData['url'];
            if (url != null && url.isNotEmpty) {
              uploadedVideoUrl = url;
              debugPrint('视频上传成功: $url');
            }
          }
        } catch (e) {
          debugPrint('视频上传失败: $e');
        }
      }

      // 去除重复标签并确保至少有一个标签
      List<PostTag> finalTags = selectedTags.toSet().toList(); // 使用Set去重
      if (finalTags.isEmpty) {
        // 获取当前圈子类型的第一个可用标签作为默认标签
        final availableTags = logic.getTagsByType(selectedCircleType);
        if (availableTags.isNotEmpty) {
          finalTags.add(availableTags.first);
        } else {
          // 如果没有可用标签，创建一个默认标签
          final defaultTag = PostTag(
            id: '${selectedCircleType.value}_default',
            name: selectedCircleType.displayName,
            type: selectedCircleType,
            isDefault: true,
          );
          finalTags.add(defaultTag);
        }
      }

      final post = CirclePost(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        userId: 'current_user_id',
        userName: '当前用户',
        userAvatar: '',
        content: _contentController.text.trim(),
        images: uploadedImageUrls, // 使用上传后的URL
          // 新增：视频列表（如果有）
        videos: uploadedVideoUrl != null ? [uploadedVideoUrl] : [],
        tags: finalTags,
        createdAt: DateTime.now(),
         // 新增：位置字段（如果选择了位置）
        locationLatitude: logic.selectedLocation.value?.latitude,
        locationLongitude: logic.selectedLocation.value?.longitude,
        locationAddress: logic.selectedLocationAddress.value.isNotEmpty
            ? logic.selectedLocationAddress.value
            : null,
      );

      // 等待发布完成
      await logic.publishPost(post, selectedCircleType);
      
      // 发布成功后清空选中的图片和视频
      logic.selectedImages.clear();
      logic.selectedImageFiles.clear();
      logic.selectedVideoFile.value = null;
      
      // 关闭进度对话框
      Get.back();
      
      // 关闭弹窗并显示成功提示
      Get.back();
      
      // 刷新当前圈子类型的帖子列表
      await logic.refreshPosts(selectedCircleType);
      debugPrint("发布成功并刷新列表");
    } catch (e) {
      // 关闭进度对话框
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      // 发布失败时不关闭弹窗，让用户可以重试
      debugPrint('发布失败: $e');
      Get.snackbar('发布失败', e.toString());
    }
  }

  // 选择图片
  void _selectImages() async {
    try {
      // 检查当前已选择的图片数量
      final currentCount = logic.selectedImageFiles.length;
      if (currentCount >= 9) {
        IMViews.showToast('最多只能选择9张图片');
        return;
      }

      final ImagePicker picker = ImagePicker();
      final List<XFile> images = await picker.pickMultiImage(
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 80,
      );
      
      if (images.isNotEmpty) {
        // 选择图片时清空视频
        logic.selectedVideoFile.value = null;
        logic.videoThumbnailPath.value = null;
        
        // 计算可以添加的图片数量
        final remainingSlots = 9 - currentCount;
        final imagesToAdd = images.take(remainingSlots).toList();
        
        // 直接保存本地文件到状态中，不立即上传
        logic.selectedImageFiles.addAll(imagesToAdd);
        
        if (images.length > remainingSlots) {
          IMViews.showToast('已选择 ${imagesToAdd.length} 张图片，最多只能选择9张');
        } else {
          IMViews.showToast('已选择 ${imagesToAdd.length} 张图片');
        }
      }
    } catch (e) {
      debugPrint('选择图片失败: $e');
      IMViews.showToast('选择图片失败: $e');
    }
  }

  // 构建已选择图片的网格预览
  Widget _buildSelectedImagesGrid() {
    return Container(
      constraints: BoxConstraints(
        maxHeight: 400.h, // 增加最大高度以容纳3行图片
      ),
      child: SingleChildScrollView(
        child: GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 8.w,
            mainAxisSpacing: 8.w,
            childAspectRatio: 1.0,
          ),
          itemCount: logic.selectedImageFiles.length,
          itemBuilder: (context, index) {
            return _buildImagePreviewItem(logic.selectedImageFiles[index], index);
          },
        ),
      ),
    );
  }

  // 构建单个图片预览项
  Widget _buildImagePreviewItem(XFile imageFile, int index) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(
          color: Styles.c_E8EAEF,
          width: 1,
        ),
      ),
      child: Stack(
        children: [
          // 本地图片缩略图
          ClipRRect(
            borderRadius: BorderRadius.circular(7.r),
            child: Image.file(
              File(imageFile.path),
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  color: Styles.c_F0F2F6,
                  child: Icon(
                    Icons.broken_image,
                    color: Styles.c_8E9AB0,
                    size: 24.w,
                  ),
                );
              },
            ),
          ),
          
          // 删除按钮
          Positioned(
            top: 4.w,
            right: 4.w,
            child: GestureDetector(
              onTap: () => _removeImage(index),
              child: Container(
                width: 20.w,
                height: 20.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.6),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 12.w,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 删除图片
  void _removeImage(int index) {
    logic.selectedImageFiles.removeAt(index);
  }

  // 选择视频
  void _selectVideo() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? video = await picker.pickVideo(source: ImageSource.gallery);
      
      if (video != null) {
        // 选择视频时清空图片
        logic.selectedImageFiles.clear();
        
        // 每次只能选择一个视频，替换之前的选择
        logic.selectedVideoFile.value = video;
        
        // 生成视频缩略图
        final thumbnailPath = await VideoThumbnail.thumbnailFile(
          video: video.path,
          thumbnailPath: (await getTemporaryDirectory()).path,
          imageFormat: ImageFormat.JPEG,
          maxHeight: 200,
          quality: 75,
        );
        
        if (thumbnailPath != null) {
          logic.videoThumbnailPath.value = thumbnailPath;
        }
        
        IMViews.showToast('已选择视频');
        debugPrint('选择了视频: ${video.path}');
      }
    } catch (e) {
      debugPrint('选择视频失败: $e');
      IMViews.showToast('选择视频失败: $e');
    }
  }

  // 构建视频预览
  Widget _buildVideoPreview() {
    final videoFile = logic.selectedVideoFile.value;
    if (videoFile == null) return const SizedBox.shrink();
    
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      width: MediaQuery.of(context).size.width-100, // 宽度为页面宽度
      height: MediaQuery.of(context).size.width-100, // 高度等于宽度，形成正方形
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(
          color: Styles.c_E8EAEF,
          width: 1,
        ),
      ),
      child: Stack(
        children: [
          // 视频缩略图
          Obx(() {
            final thumbnailPath = logic.videoThumbnailPath.value;
            if (thumbnailPath != null && File(thumbnailPath).existsSync()) {
              return ClipRRect(
                borderRadius: BorderRadius.circular(7.r),
                child: Stack(
                  children: [
                    Image.file(
                      File(thumbnailPath),
                      width: double.infinity,
                      height: double.infinity,
                      fit: BoxFit.cover,
                    ),
                    // 播放按钮覆盖层
                    Container(
                      width: double.infinity,
                      height: double.infinity,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.3),
                        borderRadius: BorderRadius.circular(7.r),
                      ),
                      child: Center(
                        child: Container(
                          width: 50.w,
                          height: 50.w,
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.6),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.play_arrow,
                            color: Colors.white,
                            size: 30.w,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            } else {
              // 缩略图生成中或失败时的占位符
              return Container(
                width: double.infinity,
                height: double.infinity,
                decoration: BoxDecoration(
                  color: Styles.c_F0F2F6,
                  borderRadius: BorderRadius.circular(7.r),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.play_circle_outline,
                      color: Styles.c_8E9AB0,
                      size: 40.w,
                    ),
                    8.verticalSpace,
                    Text(
                      '视频已选择',
                      style: TextStyle(
                        color: Styles.c_8E9AB0,
                        fontSize: 12.sp,
                      ),
                    ),
                  ],
                ),
              );
            }
          }),
          
          // 删除按钮
          Positioned(
            top: 2.w,
            right: 2.w,
            child: GestureDetector(
              onTap: () => _removeVideo(),
              child: Container(
                width: 16.w,
                height: 16.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.6),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 10.w,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 移除视频
  void _removeVideo() {
    logic.selectedVideoFile.value = null;
    logic.videoThumbnailPath.value = null;
  }

  // 选择位置
  void _selectLocation() async {
    // 直接调用地图位置选择器
    _openMapLocationPicker();
  }

  void _openMapLocationPicker() async {
    final result = await Get.to(() => LocationPickerView(
      initialPosition: null,
      initialAddress: null,
    ));
    
    if (result != null && result is Map<String, dynamic>) {
      final LatLng position = result['position'];
      final String address = result['address'];
      
      // 确认选择的位置
      _confirmLocation(Position(
        latitude: position.latitude,
        longitude: position.longitude,
        timestamp: DateTime.now(),
        accuracy: 0,
        altitude: 0,
        heading: 0,
        speed: 0,
        speedAccuracy: 0,
        altitudeAccuracy: 0,
        headingAccuracy: 0,
      ), address);
    }
  }
  
  
  void _confirmLocation(Position position, String address) {
    // 将位置信息保存到logic中
    logic.selectedLocation.value = position;
    logic.selectedLocationAddress.value = address;
    
    // IMViews.showToast('位置已选择: $address');
    print('选择的位置: 经度=${position.longitude}, 纬度=${position.latitude}, 地址=$address');
  }

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }
}

// 通知面板组件
class _NotificationPanel extends StatelessWidget {
  final logic = Get.find<NotificationLogic>();

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.7,
      decoration: BoxDecoration(
        color: Styles.c_FFFFFF,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Column(
        children: [
          // 拖拽指示器
          Container(
            margin: EdgeInsets.only(top: 8.h),
            width: 40.w,
            height: 4.h,
            decoration: BoxDecoration(
              color: Styles.c_8E9AB0,
              borderRadius: BorderRadius.circular(2.r),
            ),
          ),
          // 标题栏
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
            child: Row(
              children: [
                Text(
                  '通知',
                  style: TextStyle(
                    color: Styles.c_0C1C33,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Spacer(),
                Obx(() => logic.unreadNotificationCount.value > 0
                    ? GestureDetector(
                        onTap: () {
                          logic.markAllNotificationsAsRead();
                        },
                        child: Text(
                          '全部已读',
                          style: TextStyle(
                            color: Styles.c_1B72EC,
                            fontSize: 14.sp,
                          ),
                        ),
                      )
                    : const SizedBox.shrink()),
                8.horizontalSpace,
                GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: Icon(
                    Icons.close,
                    color: Styles.c_8E9AB0,
                    size: 24.w,
                  ),
                ),
              ],
            ),
          ),
          // 分隔线
          Container(
            height: 1.h,
            color: Styles.c_F8F9FA,
          ),
          // 通知列表
          Expanded(
            child: Obx(() {
              if (logic.notifications.isEmpty) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.notifications_none,
                        size: 64.w,
                        color: Styles.c_8E9AB0,
                      ),
                      16.verticalSpace,
                      Text(
                        '暂无通知',
                        style: TextStyle(
                          color: Styles.c_8E9AB0,
                          fontSize: 16.sp,
                        ),
                      ),
                    ],
                  ),
                );
              }
              
              return ListView.builder(
                padding: EdgeInsets.zero,
                itemCount: logic.notifications.length,
                itemBuilder: (context, index) {
                  return _buildNotificationItem(logic.notifications[index]);
                },
              );
            }),
          ),
        ],
      ),
    );
  }

  // 构建通知项
  Widget _buildNotificationItem(PostNotification notification) {
    return GestureDetector(
      onTap: () {
        logic.markNotificationAsRead(notification.id);
        // 可以跳转到相关帖子
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color: notification.isRead ? Styles.c_FFFFFF : Styles.c_F8F9FA.withOpacity(0.5),
          border: Border(
            bottom: BorderSide(
              color: Styles.c_F8F9FA,
              width: 0.5,
            ),
          ),
        ),
        child: Row(
          children: [
            // 用户头像
            AvatarView(
              url: notification.fromUserAvatar,
              text: logic.getNotificationDisplayName(notification),
              width: 40.w,
              height: 40.h,
            ),
            12.horizontalSpace,
            // 通知内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    logic.getNotificationDisplayText(notification),
                    style: TextStyle(
                      color: Styles.c_0C1C33,
                      fontSize: 14.sp,
                      fontWeight: notification.isRead ? FontWeight.normal : FontWeight.w500,
                    ),
                  ),
                  if (notification.targetContent != null) ...[
                    4.verticalSpace,
                    Text(
                      '"${notification.targetContent}"',
                      style: TextStyle(
                        color: Styles.c_8E9AB0,
                        fontSize: 12.sp,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                  4.verticalSpace,
                  Text(
                    notification.timeAgo,
                    style: TextStyle(
                      color: Styles.c_8E9AB0,
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
            ),
            // 通知类型图标
            Container(
              padding: EdgeInsets.all(6.w),
              decoration: BoxDecoration(
                color: _getNotificationTypeColor(notification.type).withOpacity(0.1),
                borderRadius: BorderRadius.circular(6.r),
              ),
              child: Icon(
                _getNotificationTypeIcon(notification.type),
                color: _getNotificationTypeColor(notification.type),
                size: 16.w,
              ),
            ),
            8.horizontalSpace,
            // 删除按钮
            GestureDetector(
              onTap: () {
                logic.deleteNotification(notification.id);
              },
              child: Icon(
                Icons.close,
                color: Styles.c_8E9AB0,
                size: 18.w,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 获取通知类型图标
  IconData _getNotificationTypeIcon(NotificationType type) {
    switch (type) {
      case NotificationType.like:
        return Icons.favorite;
      case NotificationType.comment:
        return Icons.comment;
      case NotificationType.reply:
        return Icons.reply;
      case NotificationType.mention:
        return Icons.alternate_email;
      case NotificationType.follow:
        return Icons.person_add;
      case NotificationType.system:
        return Icons.info;
    }
  }

  // 获取通知类型颜色
  Color _getNotificationTypeColor(NotificationType type) {
    switch (type) {
      case NotificationType.like:
        return Colors.red;
      case NotificationType.comment:
        return Colors.blue;
      case NotificationType.reply:
        return Colors.green;
      case NotificationType.mention:
        return Colors.orange;
      case NotificationType.follow:
        return Colors.purple;
      case NotificationType.system:
        return Colors.grey;
    }
  }
}

// 编辑帖子对话框
class _EditPostDialog extends StatefulWidget {
  final CirclePost post;
  
  const _EditPostDialog({required this.post});
  
  @override
  _EditPostDialogState createState() => _EditPostDialogState();
}

class _EditPostDialogState extends State<_EditPostDialog> {
  late TextEditingController _contentController;
  final logic = Get.find<NotificationLogic>();
  late List<PostTag> selectedTags;
  late CircleType postCircleType; // 添加帖子圈子类型字段
  
  @override
  void initState() {
    super.initState();
    _contentController = TextEditingController(text: widget.post.content);
    selectedTags = List.from(widget.post.tags);
    
    // 获取帖子的圈子类型
    postCircleType = widget.post.circleType ?? _inferCircleTypeFromTags();
  }
  
  // 从标签推断圈子类型
  CircleType _inferCircleTypeFromTags() {
    if (widget.post.tags.isNotEmpty) {
      // 使用第一个标签的类型作为圈子类型
      return widget.post.tags.first.type;
    }
    // 如果没有标签，默认为城市圈
    return CircleType.city;
  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
      height: Get.height * 0.8,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                TextButton(
                  onPressed: () => Get.back(),
                  child: Text('取消', style: Styles.ts_8E9AB0_14sp),
                ),
                Spacer(),
                Text('编辑帖子', style: Styles.ts_0C1C33_17sp_medium),
                Spacer(),
                TextButton(
                  onPressed: _updatePost,
                  child: Text('保存', style: Styles.ts_0C1C33_14sp_medium),
                ),
              ],
            ),
          ),
          Divider(height: 1.h),
          
          // 标签选择
          Container(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text('选择标签', style: Styles.ts_0C1C33_14sp_medium),
                    8.horizontalSpace,
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                      decoration: BoxDecoration(
                        color: Styles.c_F8F9FA,
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Text(
                        postCircleType.displayName,
                        style: TextStyle(
                          color: Styles.c_8E9AB0,
                          fontSize: 10.sp,
                        ),
                      ),
                    ),
                  ],
                ),
                8.verticalSpace,
                Obx(() => Wrap(
                  spacing: 8.w,
                  runSpacing: 8.h,
                  children: logic.getTagsByType(postCircleType).map((tag) => 
                    GestureDetector(
                      onTap: () => _toggleTag(tag),
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                        decoration: BoxDecoration(
                          color: selectedTags.contains(tag) ? Styles.c_0C1C33 : Styles.c_F8F9FA,
                          borderRadius: BorderRadius.circular(16.r),
                          border: tag.color != null
                              ? Border.all(
                                  color: Color(int.parse('0xFF${tag.color!.substring(1)}')),
                                )
                              : null,
                        ),
                        child: Text(
                          tag.name,
                          style: TextStyle(
                            color: selectedTags.contains(tag) ? Colors.white : Styles.c_0C1C33,
                            fontSize: 12.sp,
                          ),
                        ),
                      ),
                    ),
                  ).toList(),
                )),
              ],
            ),
          ),
          
          // 内容输入
          Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: TextField(
                controller: _contentController,
                maxLines: null,
                expands: true,
                textAlignVertical: TextAlignVertical.top,
                decoration: InputDecoration(
                  hintText: '编辑帖子内容...',
                  border: InputBorder.none,
                  hintStyle: TextStyle(
                    color: Styles.c_8E9AB0,
                    fontSize: 16.sp,
                  ),
                ),
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Styles.c_0C1C33,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  void _toggleTag(PostTag tag) {
    setState(() {
      if (selectedTags.contains(tag)) {
        selectedTags.remove(tag);
      } else {
        // 确保不会添加重复标签
        if (!selectedTags.any((existingTag) => existingTag.id == tag.id)) {
          selectedTags.add(tag);
        }
      }
    });
  }
  
  Future<void> _updatePost() async {
    if (_contentController.text.trim().isEmpty) {
      Get.snackbar('提示', '请输入帖子内容');
      return;
    }
    
    // 去除重复标签并确保至少有一个标签
    List<PostTag> finalTags = selectedTags.toSet().toList(); // 使用Set去重
    if (finalTags.isEmpty) {
      final availableTags = logic.getTagsByType(postCircleType);
      if (availableTags.isNotEmpty) {
        finalTags.add(availableTags.first);
      }
    }
    
    try {
      await logic.updatePost(
        widget.post.id,
        _contentController.text.trim(),
        finalTags,
      );
      Get.back();
    } catch (e) {
      debugPrint('更新失败: $e');
    }
  }
  
  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }
}


class _InlineVideoPlayer extends StatefulWidget {
  const _InlineVideoPlayer({Key? key, required this.url}) : super(key: key);
  final String url;

  @override
  State<_InlineVideoPlayer> createState() => _InlineVideoPlayerState();
}

class _InlineVideoPlayerState extends State<_InlineVideoPlayer> {
  late final VideoPlayerController _controller;
  bool _initialized = false;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.networkUrl(Uri.parse(widget.url))
      ..setLooping(true)
      ..initialize().then((_) {
        if (mounted) {
          setState(() => _initialized = true);
        }
      });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!_initialized) {
      return AspectRatio(
        aspectRatio: 16 / 9,
        child: Container(
          decoration: BoxDecoration(
            color: Styles.c_F0F2F6,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: const Center(child: CircularProgressIndicator()),
        ),
      );
    }
    return Stack(
      alignment: Alignment.center,
      children: [
        AspectRatio(
          aspectRatio: _controller.value.aspectRatio == 0
              ? (16 / 9)
              : _controller.value.aspectRatio,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8.r),
            child: VideoPlayer(_controller),
          ),
        ),
        GestureDetector(
          onTap: () {
            if (_controller.value.isPlaying) {
              _controller.pause();
            } else {
              _controller.play();
            }
            setState(() {});
          },
          child: Container(
            width: 48.w,
            height: 48.w,
            decoration: BoxDecoration(
              color: Colors.black45,
              shape: BoxShape.circle,
            ),
            child: Icon(
              _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }
}